myApp.filter('applyFilter', [function () {
    return function (applyList, planName) {
        var list = [];
        angular.forEach(applyList, function (apply) {
            if (planName == '') {
                list.push(apply);
            } else if ((apply.plan_name != null && apply.plan_name.toLowerCase().indexOf(planName.toLowerCase()) != -1)
                || (apply.agent_ip != null && apply.agent_ip.toLowerCase().indexOf(planName.toLowerCase()) != -1)) {
                list.push(apply);
            }
        });
        return list;
    };
}]);
myApp.filter('applyListFilter', [function () {
    return function (applyList) {
        var list = [];
        var userRole = getUserRole();
        var userAccount = getUserAccount();
        if (arrayContains(userRole, 'admin') || arrayContains(userRole, 'audit') || arrayContains(userRole, 'assign')) {
            return applyList;
        }
        angular.forEach(applyList, function (apply) {
            if (apply.applicant_id != null && apply.applicant_id == getUserId()) {
                list.push(apply);
            } else if (apply.planInfo != null) {
                var members = apply.planInfo.members;
                angular.forEach(members, function (member) {
                    if (member.account == userAccount) {
                        list.push(apply);
                        return;
                    }
                });
            }
        });
        return list;
    };
}]);
myApp.controller('ucAlylistController', function ($scope, $uibModal, $stateParams, ngDialog, $http, $filter) {
    $scope.info = {};
    //搜索框默认值
    $scope.info.plan_name = $stateParams.plan_name;
    $scope.userList = [];
    $scope.info.recordlist = [];
    $scope.status = [];
    $scope.info.isOnlyoverdue = false;
    $scope.info.isOnlyOneMouth = true;

    $scope.info.userRole = getUserRole();

    $scope.roleContain = function (role) {
        return arrayContains($scope.info.userRole, role);
    };

    $scope.isIntegration = function (ip) {
        if (ip == null) {
            return false;
        }
        return arrayContains(integration_agent_list, ip);
    };

    $scope.record_list = function () {
        $http.get(ucloud_master_url + '/api/v1/apply_record/?token_id=' + getTokenId() + '&isOnlyoverdue=' + $scope.info.isOnlyoverdue + "&isOnlyOneMouth=" + $scope.info.isOnlyOneMouth).success(function (data) {
            var list = data.data;
            var plans = '';
            for (var i in list) {
                if (list[i].plan_id == null || list[i].plan_id == '') {
                    continue
                }
                plans += list[i].plan_id + ',';
            }
            plans = plans.substring(0, plans.length - 1);
            $http.post(beetle_plan_url + '/project_plan/getPlanList', {
                token_id: getTokenId(),
                isShowOnline: true,
                plan_id: plans
            }).success(function (d) {
                angular.forEach(list, function (apply) {
                    apply.planInfo = null;
                    if (apply.plan_id != null && apply.plan_id != '') {
                        angular.forEach(d.data, function (plan) {
                            if (apply.plan_id == plan.plan_id) {
                                apply.planInfo = plan;
                                return;
                            }
                        })
                    }
                });
                $scope.info.recordlist = $filter('applyListFilter')(list);
            });
        })
    };
    $scope.record_list();

    $scope.total = $scope.info.recordlist.length;
    $scope.page = {size: 20, index: 1};

    $scope.add = function () {
        var modalInstance = $uibModal.open({
            animation: true,
            templateUrl: 'add.html',
            controller: 'addCtrl'

        });
        modalInstance.result.then(function (result) {
                if (result == 'cancel') {
                    $scope.record_list();
                }
            },
            function (reason) {
                if (reason == 'cancel') {
                    $scope.record_list();
                }
            });
    };

    $scope.recoverAgent = function (apply) {
        openDialog(ngDialog, $scope, "ucloud将被回收，请确认!", true, function (val) {
            if (!val) {
                return;
            }
            $http.get(ucloud_master_url + '/api/v1/apply_record/recoverAgent?token_id=' + getTokenId() + '&record_id=' + apply.record_id).success(function (data) {
                if (data.success == true) {
                    $scope.record_list();
                } else {
                    alert(data.msg);

                }
            })
        })
    };

    $scope.Examination = function (i) {
        var info = {};
        info = i;
        var modalInstance = $uibModal.open({
            animation: true,
            templateUrl: 'Examination.html',
            controller: 'ExaminationCtrl',
            resolve: {
                info: function () {
                    return info;
                }
            }
        });
        modalInstance.result.then(function (result) {
                if (result == 'cancel') {
                    $scope.record_list();
                }
            },
            function (reason) {
                if (reason == 'cancel') {
                    $scope.record_list(info);
                }
            });
    };

    $scope.toAgent = function (ip) {
        window.location.href = "#/menu/newucList/" + ip;
    }

});


myApp.controller('ExaminationCtrl', function ($scope, $uibModalInstance, info, $http) {
    $scope.info = info;
    $scope.info.isfalse = false;
    $scope.info.level_name = "";
    $scope.level_list = [];
    $scope.ucloud_agent = [];
    $scope.info.ip = "";
    if ($scope.info.status == "申请中") {
        $scope.info.typeName = "0";//审批
        $scope.info.added_desc = "";
    } else if ($scope.info.status != "申请中") {
        $scope.info.typeName = "1";//分配
    }

    if ($scope.info.typeName == "0") {
        $.ajax({
            type: "GET",
            url: ucloud_master_url + "/api/v1/load_level/?token_id=" + getTokenId(),
            async: false,
            success: function (data) {

                $scope.level_list = data.data;

            }
        });
    }
    if ($scope.info.typeName == "1") {
        $.ajax({
            type: 'GET',
            url: ucloud_master_url + '/api/v1/agent/?token_id=' + getTokenId(),
            async: false,
            success: function (data) {
                $scope.ucloud_agent = data.data
            }
        });
    }
    ;

    $scope.userName = getUserName();
    $scope.title = "";
    if ($scope.info.typeName == "0") {
        $scope.title = "审核信息";
    } else if ($scope.info.typeName == "1") {
        $scope.title = "分配虚拟机";
    }


    $scope.save = function () {

        if ($scope.info.typeName == "0") {

            if ($scope.info.added_desc == '') {
                alert('请填写补充说明');
                return false;
            }
            if ($scope.info.level_name == '') {
                alert('请选择硬件规模!');
                return false;
            }

            $http.get(ucloud_master_url + '/api/v1/apply_record/audit?audit_id=' + getUserId() + '&added_desc=' + $scope.info.added_desc + '&record_id=' + $scope.info.record_id + '&token_id=' + getTokenId() + '&level_name=' + $scope.info.level_name + '&audit_name=' + getUserName()).success(
                function (data) {
                    if (data.success == true) {
                        $uibModalInstance.dismiss('cancel');
                    } else {
                        alert(data.msg);
                    }
                });
        } else if ($scope.info.typeName == "1") {
            if ($scope.info.ip == "") {
                alert('请选择ucloud_ip');
                return false;
            }
            $http.get(ucloud_master_url + '/api/v1/apply_record/assign?record_id=' + $scope.info.record_id + '&token_id=' + getTokenId() + '&agent_ip=' + $scope.info.ip).success(function (data) {
                if (data.success == true) {
                    if ($scope.info.isfalse == true) {
                        $uibModalInstance.dismiss('cancel');
                        window.location.href = "#/menu/newucList/" + $scope.info.ip;

                    } else {
                        $uibModalInstance.dismiss('cancel');
                    }

                } else {
                    alert(data.msg);
                }

            })


        }


    };


    $scope.cancel = function () {
        // 关闭弹出框
        $uibModalInstance.dismiss('cancel');
    };
});

myApp.controller('addCtrl', function ($scope, $uibModalInstance, $http, $filter) {
    $scope.info = [];
    $scope.info.desc = "";
    $scope.info.type = "DEV";
    $scope.info.selectPlan = '';
    $scope.info.startExceptTime = '';
    $scope.info.endExceptTime = '';
    $scope.startTime = false;
    $scope.endTime = false;
    $scope.userName = getUserName();

    $scope.info.planList = [];

    $http.get(beetle_plan_url + '/project_plan/getPlanList?token_id=' + getTokenId() + '&isShowOnline=false').success(function (data) {
        $scope.info.planList = data.data;
        if ($scope.info.planList.length > 0) {
            $scope.info.selectPlan = $scope.info.planList[0];
        }
    });

    $scope.save = function () {
        var plan_Id = '';
        var plan_Name = '';

        if ($scope.info.startExceptTime == '') {
            $scope.startTime = true;
            return false;
        } else {
            $scope.startTime = false;
        }
        if ($scope.info.endExceptTime == '') {
            $scope.endTime = true;
            return false;
        } else {
            $scope.endTime = false;
        }
        if ($scope.info.endExceptTime < $scope.info.startExceptTime) {
            alert("结束时间小于开始时间，请确认");
            return false;

        }
        if ($scope.info.selectPlan == '') {
            $scope.showPlanError = true;
            return false;
        } else {
            $scope.showPlanError = false;
        }

        if ($scope.info.selectPlan != '') {
            plan_Id = $scope.info.selectPlan.plan_id;
            plan_Name = $scope.info.selectPlan.plan_name;
            $http.get(ucloud_master_url + '/api/v1/apply_record/add?type=' + $scope.info.type + '&applicant_id=' + getUserId() + '&expect_recover_date=' + $filter('date')($scope.info.endExceptTime, "yyyy-MM-dd") + '&token_id=' + getTokenId() + '&plan_name=' + plan_Name + '&plan_id=' + plan_Id + '&start_date=' + $filter('date')($scope.info.startExceptTime, "yyyy-MM-dd") + '&applicant_name=' + getUserName() + '&desc=' + $scope.info.desc).success(function (data) {
                if (data.success == true) {
                    $uibModalInstance.dismiss('cancel');
                } else {
                    alert(data.msg);
                }
            })
        } else {
            $http.get(ucloud_master_url + '/api/v1/apply_record/add?type=' + $scope.info.type + '&applicant_id=' + getUserId() + '&expect_recover_date=' + $filter('date')($scope.info.endExceptTime, "yyyy-MM-dd") + '&token_id=' + getTokenId() + '&start_date=' + $filter('date')($scope.info.startExceptTime, "yyyy-MM-dd") + '&applicant_name=' + getUserName() + '&desc=' + $scope.info.desc).success(function (data) {
                if (data.success == true) {
                    $uibModalInstance.dismiss('cancel');
                } else {
                    alert(data.msg);
                }
            })
        }


    };

    $scope.cancel = function () {
        // 关闭弹出框
        $uibModalInstance.dismiss('cancel');
    };

});